Vue Js Window Resize Event:In Vue.js, the window resize event can be used to detect when the browser window is resized. This can be useful for dynamically adjusting the layout of the application based on the size of the window. To add an event listener for window resize in Vue.js, you can use the mounted() lifecycle hook to attach a listener to the window object. Within the listener, you can use Vue.js methods and data to dynamically update the application’s layout based on the new window size.
How can I detect and handle window resize events in Vue js?
This code is a Vue.js application that displays the width of the browser window using the window.innerWidth
property.
In the data()
method, the windowWidth
variable is initialized with the current width of the browser window.
The created()
lifecycle hook is used to add an event listener for the resize
event of the window
object, which triggers the handleResize()
method when the window is resized.
In the handleResize()
method, the windowWidth
variable is updated with the current width of the browser window.
The destroyed()
lifecycle hook is used to remove the event listener when the component is destroyed to prevent memory leaks.
Overall, this code allows the width of the browser window to be dynamically updated in the Vue app whenever the window is resized.
Vue Js Window Resize Event Example
<div id="app">
<p>Window width: {{ windowWidth }}</p>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
windowWidth: window.innerWidth,
};
},
created() {
window.addEventListener("resize", this.handleResize);
},
destroyed() {
window.removeEventListener("resize", this.handleResize);
},
methods: {
handleResize() {
this.windowWidth = window.innerWidth;
},
},
})
app.mount('#app')
</script>